package cn.lili.modules.goods_auth.serviceImpl;

import cn.hutool.http.HttpUtil;
import cn.lili.aop.annotation.AuthGoodsOpenLog;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.*;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.goods.client.GoodsClient;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.goods.entity.dto.GoodsSearchParams;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsMarketEnum;
import cn.lili.modules.goods_auth.manage.GoodsAuthManage;
import cn.lili.modules.goods_auth.service.AuthSpaceGoodsService;
import cn.lili.modules.goods_auth.service.GoodsAuthOpenApiService;
import cn.lili.modules.goods_auth.service.GoodsAuthService;
import cn.lili.modules.system.entity.dos.*;
import cn.lili.modules.system.entity.enums.AuthTypeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;

@Slf4j
@Service
@AllArgsConstructor
public class GoodsAuthOpenApiServiceImpl implements GoodsAuthOpenApiService {

    private final GoodsAuthService goodsAuthService;
    private final AuthSpaceGoodsService authSpaceGoodsService;
    private final GoodsClient goodsClient;
    private final GoodsAuthManage goodsAuthManage;

    /**
     * 拉取商品
     *
     * @param goodsAuthOpen 拉去商品请求参数
     * @return 返回商品信息
     */
    @AuthGoodsOpenLog(OperateType = "拉取商品")
    @Override
    public ResultMessage<Object> getAuthGoods(GoodsAuthOpen goodsAuthOpen) throws Exception {
        Assert.notNull(goodsAuthOpen.getAppid(), "appid不能为空");
        //Assert.notNull(goodsAuthOpen.getSign(),"sign不能为空");

        // 查询授权配置
        LiAuth liAuth = goodsAuthService.getLiAuthByAppid(goodsAuthOpen.getAppid());
        Assert.notNull(liAuth, "授权获取失败");
        Assert.isTrue(liAuth.getType().equals(AuthTypeEnum.NORMAL.getCode()), "授权已被冻结");

        // 验证签名
        if (StringUtils.isNotEmpty(goodsAuthOpen.getSign())) {
            goodsAuthManage.verifySignature(goodsAuthOpen.getSign(), liAuth, goodsAuthOpen);
        }

        // 判断权限
        Assert.isTrue(liAuth.getAuth().contains(goodsAuthOpen.getAuth()), "您的权限不足");

        // 获取商品数据
        Page<Goods> goodsPage;
        if ("0".equals(goodsAuthOpen.getAuth())) {
            GoodsSearchParams goodsSearchParams = new GoodsSearchParams(goodsAuthOpen.getPageNumber(), goodsAuthOpen.getPageSize());
            goodsSearchParams.setAuthFlag(GoodsAuthEnum.PASS.name());
            goodsSearchParams.setMarketEnable(GoodsMarketEnum.UPPER.name());
            goodsSearchParams.setScene(SceneEnums.STORE.name());
            goodsPage = goodsClient.queryByParams(goodsSearchParams);
        } else {
            goodsPage = goodsAuthManage.getGoodsPageBySpaceCode(goodsAuthOpen.getSpaceCode(), goodsAuthOpen.getPageNumber(), goodsAuthOpen.getPageSize());
        }

        //返回查询结果
        Map<String, Object> map = new HashMap<>();
        map.put("goodsPage", goodsPage);
        map.put("flag", System.currentTimeMillis());
        return ResultUtil.data(map);
    }

    @AuthGoodsOpenLog(OperateType = "商品变动")
    @Override
    public ResultMessage<Object> callBackGoods(GoodsAuthOpenCallback callback) {
        //根据商品ID查询授权空间商品
        List<LiAuthSpaceGoods> spaceGoodsList = authSpaceGoodsService.getLiAuthSpaceGoodsByGoodsId(callback.getGoodsId());
        if (spaceGoodsList == null || spaceGoodsList.isEmpty()) {
            return null;
        }

        //查询所有授权
        List<LiAuth> authList = goodsAuthService.getList();

        //查询具体商品数据
        GoodsSearchParams goodsSearchParams = new GoodsSearchParams();
        goodsSearchParams.setIds(Collections.singletonList(callback.getGoodsId()));
        Page<Goods> goodsPage = goodsClient.queryByParams(goodsSearchParams);

        //回调通知
        List<String> resultList = new ArrayList<>();
        authList.forEach(auth -> {
            String result = callBackPost(auth.getCallbackUrl(), JSON.toJSONString(goodsPage.getRecords().get(0)));
            resultList.add(result);
        });
        return ResultUtil.data(resultList);
    }


    /**
     * 发送请求
     *
     * @param callbackUrl 回调地址
     * @param sendJson    发送json
     * @return 返回结果
     */
    public String callBackPost(String callbackUrl, String sendJson) {
        String result = null;
        try {
            log.info("商品变动--发送请求参数:{}", sendJson);
            result = HttpUtil.post(callbackUrl, JSONObject.parseObject(sendJson));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return result;
    }
}